package org.bdware.doip.core.codec.packet;

import io.netty.channel.ChannelHandlerContext;
import org.bdware.doip.core.doipMessage.MessageEnvelope;

import java.util.HashMap;

public class PassiveEnvelopeSenderBuffer extends AbstractEnvelopeSendBuffer{

    HashMap<Integer, MessageEnvelope> envelopeBuffer;
    public ChannelHandlerContext ctx;

    public PassiveEnvelopeSenderBuffer(int requestId, ChannelHandlerContext ctx) {
        super(requestId);
        this.ctx = ctx;
        envelopeBuffer = new HashMap<>();
    }

    @Override
    public void pushToBuffer(MessageEnvelope env) {
        envelopeBuffer.put(env.sequenceNumber,env);
    }

    @Override
    public boolean receiveAck(MessageEnvelope env) {
        if(isCompleted) return true;
        if(env.sequenceNumber == -1){
            isCompleted = true;
        }else{
            ctx.writeAndFlush(envelopeBuffer.get(env.sequenceNumber));
        }
        return isCompleted;
    }
}
